from flask import Blueprint, request, jsonify, session, current_app
from utils.auth import login_required, get_current_user_id
from utils.user_errors import UserError, handle_user_error
from utils.logger import get_logger

logger = get_logger(__name__)

# 创建用户路由蓝图
user_api = Blueprint('user_api', __name__)

@user_api.route('/api/user/register', methods=['POST'])
def register():
    """用户注册接口"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                "success": False,
                "message": "无效的请求数据"
            }), 400

        required_fields = ['username', 'email', 'password']
        if not all(field in data for field in required_fields):
            return jsonify({
                "success": False,
                "message": "缺少必要的注册信息"
            }), 400

        success, message, user_data = current_app.user_service.register(
            username=data['username'],
            email=data['email'],
            password=data['password']
        )

        if success and user_data:
            # 注册成功后自动登录
            session['user_id'] = user_data['id']
            session['username'] = user_data['username']
            return jsonify({
                "success": True,
                "message": message,
                "data": user_data
            })
        
        return jsonify({
            "success": False,
            "message": message
        }), 400

    except Exception as e:
        logger.error(f"Registration error: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "注册过程中发生错误"
        }), 500

@user_api.route('/api/user/login', methods=['POST'])
def login():
    """用户登录接口"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                "success": False,
                "message": "无效的请求数据"
            }), 400

        if 'username' not in data or 'password' not in data:
            return jsonify({
                "success": False,
                "message": "请提供用户名和密码"
            }), 400

        success, message, user_data = current_app.user_service.login(
            username=data['username'],
            password=data['password']
        )

        if success and user_data:
            session['user_id'] = user_data['id']
            session['username'] = user_data['username']
            return jsonify({
                "success": True,
                "message": message,
                "data": user_data
            })

        return jsonify({
            "success": False,
            "message": message
        }), 401

    except Exception as e:
        logger.error(f"Login error: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "登录过程中发生错误"
        }), 500

@user_api.route('/api/user/logout', methods=['POST'])
@login_required
def logout():
    """用户注销接口"""
    try:
        session.clear()
        return jsonify({
            "success": True,
            "message": "已成功注销"
        })
    except Exception as e:
        logger.error(f"Logout error: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "注销过程中发生错误"
        }), 500

@user_api.route('/api/user/profile', methods=['GET'])
@login_required
def get_profile():
    """获取用户个人信息"""
    try:
        user_id = get_current_user_id()
        user_data = current_app.user_service.get_user_by_id(user_id)
        
        if user_data:
            return jsonify({
                "success": True,
                "data": user_data
            })
        
        return jsonify({
            "success": False,
            "message": "未找到用户信息"
        }), 404

    except Exception as e:
        logger.error(f"Error fetching user profile: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "获取用户信息时发生错误"
        }), 500

@user_api.route('/api/user/profile', methods=['PUT'])
@login_required
def update_profile():
    """更新用户个人信息"""
    try:
        data = request.get_json()
        if not data:
            return jsonify({
                "success": False,
                "message": "无效的请求数据"
            }), 400

        user_id = get_current_user_id()
        success, message, user_data = current_app.user_service.update_user_info(user_id, data)

        if success and user_data:
            return jsonify({
                "success": True,
                "message": message,
                "data": user_data
            })

        return jsonify({
            "success": False,
            "message": message
        }), 400

    except Exception as e:
        logger.error(f"Error updating user profile: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "更新用户信息时发生错误"
        }), 500

@user_api.route('/api/user/deactivate', methods=['POST'])
@login_required
def deactivate_account():
    """注销账户"""
    try:
        user_id = get_current_user_id()
        success, message = current_app.user_service.deactivate_account(user_id)

        if success:
            session.clear()
            return jsonify({
                "success": True,
                "message": message
            })

        return jsonify({
            "success": False,
            "message": message
        }), 400

    except Exception as e:
        logger.error(f"Error deactivating account: {str(e)}", exc_info=True)
        return jsonify({
            "success": False,
            "message": "注销账户时发生错误"
        }), 500

# 注册错误处理器
@user_api.errorhandler(UserError)
def handle_user_error_handler(error):
    """处理用户相关的错误"""
    return handle_user_error(error)